package com.imist.controller;

import com.imist.dao.CourseDao;
import com.imist.entity.Course;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class CourseController {
    @Autowired
    private CourseDao courseDao;

    /**
     * 添加课程
     * @param course
     * @return
     */
    //@PostMapping 需要Spring4.3 之后的版本的才能使用
    @RequestMapping(value = "/add" , method = RequestMethod.POST )
    public String addCourse(Course course){
        courseDao.addCourse(course);
        return "redirect:getAll";
    }

    /**
     * 查询所有的课程并且显示
     * @param course
     * @return
     */
    @RequestMapping(value = "/getAll" , method = RequestMethod.GET )
    public ModelAndView getAll(Course course){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("courses",courseDao.findAll());
        return modelAndView;
    }

    /**
     * 根据ID获取课程
     * @param id
     * @return
     */
    @RequestMapping(value = "/getById/{id}" , method = RequestMethod.GET )
    public ModelAndView getCourseById(@PathVariable("id") int id){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("edit");
        modelAndView.addObject("course",courseDao.getCourseById(id));
        return modelAndView;
    }

    /**
     * 更新课程
     * @param course
     * @return
     */
    @RequestMapping(value = "/update" , method = RequestMethod.PUT )
    public String update(Course course){
        courseDao.update(course);
        //这里可以不加 `/` 是因为getAll和update是同级的
        return "redirect:getAll";
    }

    /**
     * 删除指定ID的课程
     * 注意这里重定向要带上`/`代表从根路径开始，不然则表示从当前路径开始
     * "redirect:getAll"; ----> //http://localhost:8080/delete/getAll
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}" , method = RequestMethod.DELETE )
    public String delete(@PathVariable("id") int id){
        courseDao.delete(id);

        return "redirect:/getAll";
    }



}
